package com.whut.report;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.whut.common.ReportCommonFunc;
import com.whut.model.Allpointsave;
import com.whut.model.Profiles;
import com.whut.model.Summary;
import com.whut.model.UrlProperties;
import com.whut.parMapper.ParProblemCollectDetailMapper;
import com.whut.parMapper.ParProblemDescriptionMapper;
import com.whut.parMapper.ParSystemMapper;
import com.whut.parMapper.utils.MapperUtils;
import com.whut.service.impl.ReportServiceImpl;
import com.whut.utils.FileUtil;
import com.whut.utils.MDoc;
import com.whut.utils.pointsCalculate;
import com.whut.v_model.ProblemCollectDetail;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang3.StringUtils;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;

import javax.annotation.Resource;
import java.awt.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.List;

public class MXTQreport {
    private ParSystemMapper parSystemMapper;
    private ParProblemDescriptionMapper parProblemDescriptionMapper;
    private ParProblemCollectDetailMapper parProblemCollectDetailMapper;
    private ReportServiceImpl reportServiceImpl;
    @Resource
    private Profiles profiles;
    private MapperUtils mapperUtils;
    private UrlProperties urlProperties;
    private int checkId;
    private int projectId;
    private boolean isNew;
    public static final int WIDTH = 718;
    public static final int HEIGHT = 468;
    public MXTQreport(ParSystemMapper parSystemMapper,
                      ParProblemDescriptionMapper parProblemDescriptionMapper,
                      ParProblemCollectDetailMapper parProblemCollectDetailMapper,
                      ReportServiceImpl reportServiceImpl,
                      MapperUtils mapperUtils,
                      UrlProperties urlProperties,
                      Profiles profiles
    ) {
        this.parSystemMapper = parSystemMapper;
        this.parProblemDescriptionMapper = parProblemDescriptionMapper;
        this.parProblemCollectDetailMapper = parProblemCollectDetailMapper;
        this.reportServiceImpl = reportServiceImpl;
        this.mapperUtils=mapperUtils;
        this.urlProperties=urlProperties;
        this.urlProperties=urlProperties;
        this.profiles=profiles;
    }


    public String getMXTQreport(int checkId, int projectId, int reportType) throws UnsupportedEncodingException {

        Integer taskId = mapperUtils.getContractchecktaskMapper().getTaskIdByCheckId(checkId);

        reportServiceImpl.initWordTheme();


        DecimalFormat df = new DecimalFormat("0.00");
        DefaultPieDataset datasetPie = new DefaultPieDataset();
        DefaultCategoryDataset datasetBar = new DefaultCategoryDataset();


        Map<String, Object> dataMap = new HashMap<String, Object>();
        reportServiceImpl.initWordDate(dataMap);

        final String Bar = "各检查分项";
        //一、工程概况
        reportServiceImpl.initProjectSummaryFirstPart(projectId, dataMap);

        //二、评估结果-----（一）综合评估结果 (二)各分项评估结果
        //由checkId拿到所有第三级信息
        List<ProblemCollectDetail> thirdIdProblemDetail = parProblemCollectDetailMapper.getAllThirdInfoMXTQ(checkId);
        List<Object> allFourthList = new ArrayList<>();
        //遍历第三级
        for (int i = 0; i < thirdIdProblemDetail.size(); i++) {
            double point3 = 0;
            int thirdId = thirdIdProblemDetail.get(i).getThirdId();
            //根据第三级id拿到它之下的所有第四级，转为jsonArray。上面不转也可以。
            List<ProblemCollectDetail> fourthIdProblemDetail = parProblemCollectDetailMapper.getAllFourthInfoMXTQ(checkId, thirdId);
            String fourthCalculateInfo = JSON.toJSONString(fourthIdProblemDetail, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
            JSONArray fourthPointsCalculateArray = JSONArray.parseArray(fourthCalculateInfo);

           /*double allweight4 = 0;
           for (int v = 0; v < fourthPointsCalculateArray.size(); v++) {
               JSONObject jsonObject = fourthPointsCalculateArray.getJSONObject(v);
               double Tweight4 = 0;
               int fourthId = jsonObject.getIntValue("fourthId");
               String trueweight4 = parSystemMapper.getWeight3ByThirdId(fourthId);
               Tweight4 = pointsCalculate.getPercentInstance(trueweight4);
               allweight4 += Tweight4;
           }*/

            //遍历第四级
            for (int j = 0; j < fourthPointsCalculateArray.size(); j++) {
                Map<String, Object> allFourthMap = new HashMap<>();
                JSONObject part2InnerObject = fourthPointsCalculateArray.getJSONObject(j);
                //算第四级权重和
                double allweight4 = 0;
                List<ProblemCollectDetail> countFourthWeight = parProblemCollectDetailMapper.getAllFourthInfoMXTQ(checkId, part2InnerObject.getIntValue("thirdId"));
                //为什么还要遍历第四级？？？
                for (int v = 0; v < countFourthWeight.size(); v++) {
                    double Tweight4 = 0;
                    int fourthId = countFourthWeight.get(v).getFourthId();

                    //更改取权重的表
                    String newWeight4 = mapperUtils.getEditableweightpsMapper().getWeightByNumber(fourthId, taskId);
                    if (StringUtils.isNotBlank(newWeight4)) {
                        Tweight4 = pointsCalculate.getPercentInstance(newWeight4);
                    } else {
                        String trueweight4 = parSystemMapper.getWeight3ByThirdId(fourthId);
                        Tweight4 = pointsCalculate.getPercentInstance(trueweight4);
                    }

                    allweight4 += Tweight4;
                }
                allFourthMap.put("pName4", part2InnerObject.getString("pName4"));

                //单条记录的3、4级权重
                double weight3 = 0;
                double weight4 = 0;
                int part2FourthId = part2InnerObject.getIntValue("fourthId");
                int part2ThirdId = part2InnerObject.getIntValue("thirdId");

                //更改权重来源
                String newWeight44 = mapperUtils.getEditableweightpsMapper().getWeightByNumber(part2FourthId, taskId);
                if (StringUtils.isNotBlank(newWeight44)) {
                    weight4 = pointsCalculate.getPercentInstance(newWeight44);
                } else {
                    weight4 = pointsCalculate.getPercentInstance(part2InnerObject.getString("weight4"));
                }

                String newWeight33 = mapperUtils.getEditableweightpsMapper().getWeightByNumber(part2ThirdId, taskId);
                if (StringUtils.isNotBlank(newWeight33)) {
                    weight3 = pointsCalculate.getPercentInstance(newWeight33);
                } else {
                    weight3 = pointsCalculate.getPercentInstance(part2InnerObject.getString("weight3"));
                }

                //1、拿到四级下的所有有问题的六级数组，problemCollect
                List<ProblemCollectDetail> sixthPoints = parProblemCollectDetailMapper.getsixthPoints(checkId, part2FourthId);
                String pointName6Info = JSON.toJSONString(sixthPoints, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                JSONArray sixthPointsArray = JSONArray.parseArray(pointName6Info);

                //总减
                double calculatePoint6 = 0;
                //单项减
                double calculatePoint66 = 0;
                //总不减
                double calculateTruePoint = 0;
                List<Object> allSixthList = new ArrayList<>();
                for (int y = 0; y < sixthPointsArray.size(); y++) {
                    Map<String, Object> allSixMap = new HashMap<>();
                    JSONObject sixPointObject = sixthPointsArray.getJSONObject(y);
                    allSixMap.put("pName6", sixPointObject.getString("pName6"));
                    int deductSixthId = sixPointObject.getIntValue("sixthId");
                    float deductPointsSumFloat = parProblemCollectDetailMapper.getdeductSum(checkId, deductSixthId);
                    double deductPointsSum = Double.valueOf(String.valueOf(deductPointsSumFloat));
                    double truePoint = Double.parseDouble(sixPointObject.getString("point6"));
                    allSixMap.put("duePoint", truePoint);
                    allSixMap.put("deductPoint", deductPointsSum);
                    allSixthList.add(allSixMap);
                    if (truePoint <= deductPointsSum) {
                        calculatePoint66 = 0;
                    } else {
                        calculatePoint66 = truePoint - deductPointsSum;
                    }
                    calculateTruePoint += truePoint;
                    calculatePoint6 += calculatePoint66;
                }

                //2、无问题项得分，无问题项不扣分
                double noProblemPoint = 0;
                List<Object> noProblemSixthIdList = mapperUtils.getUncheckeditemsMapper().getNoProblemSixthId(checkId, part2InnerObject.getIntValue("fourthId"));
                String noProblemSixthIdInfo = JSON.toJSONString(noProblemSixthIdList, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                JSONArray noProblemSixthArray = JSONArray.parseArray(noProblemSixthIdInfo);
                for (int m = 0; m < noProblemSixthArray.size(); m++) {
                    Map<String, Object> allSixMap = new HashMap<>();
                    int noProblemSixthId = noProblemSixthArray.getIntValue(m);
                    allSixMap.put("pName6", parSystemMapper.getName4ByName4Id(noProblemSixthId));
                    allSixMap.put("duePoint", parSystemMapper.getPoint4ByPoint4Id(noProblemSixthId));
                    allSixMap.put("deductPoint", 0);
                    allSixthList.add(allSixMap);
                    double noProblem = Double.parseDouble(parSystemMapper.getPoint4ByPoint4Id(noProblemSixthId));
                    noProblemPoint += noProblem;
                }

                //3、prefixsystem体系里面除了problemCollect和uncheckedItems里的第六级id，未涉及
                List<Integer> wsjList = parSystemMapper.getWSJList(checkId, part2InnerObject.getIntValue("fourthId"));
                for (int g = 0; g < wsjList.size(); g++) {
                    Map<String, Object> allSixMap = new HashMap<>();
                    int wsjSixthId = wsjList.get(g);
                    allSixMap.put("pName6", parSystemMapper.getName4ByName4Id(wsjSixthId));
                    allSixMap.put("duePoint", parSystemMapper.getPoint4ByPoint4Id(wsjSixthId));
                    allSixMap.put("deductPoint", "未涉及");
                    allSixthList.add(allSixMap);
                }

                allFourthMap.put("allSixthList", allSixthList);
                System.out.println("第六级扣过的分数总分:" + calculatePoint6 + "没有问题的总分:" + noProblemPoint + "第六级总分:" + calculateTruePoint);
                double checkItemPoint= 0;
                if((calculateTruePoint + noProblemPoint)==0)  checkItemPoint=0.0;
                else  checkItemPoint = (calculatePoint6 + noProblemPoint) / (calculateTruePoint + noProblemPoint) * 100;

                point3 += checkItemPoint * (weight4 / allweight4);

                //根据最大风险等级以及数量确定分数上限，表里没数据，就取100。
                List<ProblemCollectDetail> checkItemCalcuList = parProblemCollectDetailMapper.getAllFourthInfo(checkId, part2FourthId);
                String maxFourthRiskPoint = pointsCalculate.getMaxRiskPoint(checkItemCalcuList);
                int maxFourthRiskPointNum = parProblemCollectDetailMapper.getRiskPointCount(checkId, part2FourthId, maxFourthRiskPoint);
                double limitFourhPoint = Double.parseDouble((mapperUtils.getPointlimitMapper().getLimitPointByInfo(String.valueOf(maxFourthRiskPointNum), maxFourthRiskPoint)) == null ? "100" : mapperUtils.getPointlimitMapper().getLimitPointByInfo(String.valueOf(maxFourthRiskPointNum), maxFourthRiskPoint));
                //两分数相比，即checkItemPoint不能超过pointLimit里的分数上限
                if (checkItemPoint > limitFourhPoint) {
                    checkItemPoint = limitFourhPoint;
                }
                String s = df.format(checkItemPoint);
                allFourthMap.put("point4", s);
                allFourthList.add(allFourthMap);

                //把计算出来4级的分存到allpointsave里去，number是4级的number
                int allPointSaveFourthPointCount = mapperUtils.getAllpointsaveMapper().getAllPointCountByCheckId(checkId, part2FourthId);
                if (allPointSaveFourthPointCount != 0) {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
                    Date date1 = new Date(System.currentTimeMillis());
                    String lastEditTime = formatter.format(date1);
                    mapperUtils.getAllpointsaveMapper().updateAllPoint(checkId, s, part2FourthId, lastEditTime);
                } else {
                    Allpointsave allpointsave = new Allpointsave();
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
                    Date date1 = new Date(System.currentTimeMillis());
                    allpointsave.setNewCreateTime(formatter.format(date1));
                    allpointsave.setLastEditTime(formatter.format(date1));
                    allpointsave.setProjectId(projectId);
                    allpointsave.setCheckId(checkId);
                    allpointsave.setNumber(part2FourthId);
                    allpointsave.setPoint(s);
                    mapperUtils.getAllpointsaveMapper().insert(allpointsave);
                }
            }

            //存3级的分
            String t = df.format(point3);
            int allPointSaveThirdPointCount = mapperUtils.getAllpointsaveMapper().getAllPointCountByCheckId(checkId, thirdId);
            if (allPointSaveThirdPointCount != 0) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
                Date date1 = new Date(System.currentTimeMillis());
                String lastEditTime = formatter.format(date1);
                mapperUtils.getAllpointsaveMapper().updateAllPoint(checkId, t, thirdId, lastEditTime);
            } else {
                Allpointsave allpointsave = new Allpointsave();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
                Date date1 = new Date(System.currentTimeMillis());
                allpointsave.setNewCreateTime(formatter.format(date1));
                allpointsave.setLastEditTime(formatter.format(date1));
                allpointsave.setProjectId(projectId);
                allpointsave.setCheckId(checkId);
                allpointsave.setNumber(thirdId);
                allpointsave.setPoint(t);
                mapperUtils.getAllpointsaveMapper().insert(allpointsave);
            }
        }
        dataMap.put("allFourthList", allFourthList);

        //(一)、综合评估结果
        List<Object> thirdList = new ArrayList<>();
        List<Object> glFourthList = new ArrayList<>();
        //总分（单项分*权重）
        double allPoint = 0;
        //权重和
        double allWeight = 0;

        //遍历三级的非管理行为
        for (int i = 0; i < thirdIdProblemDetail.size(); i++) {
            if (!thirdIdProblemDetail.get(i).getpName1().equals("管理行为")) {
                Map<String, Object> thirdMap = new HashMap<>();
                //取出上面刚存的第三级的分数
                String point3 = mapperUtils.getAllpointsaveMapper().getPointByCheckIdAndNumber(checkId, thirdIdProblemDetail.get(i).getThirdId());

                //更改权重来源
                int thirdId = thirdIdProblemDetail.get(i).getThirdId();
                String weight3 = mapperUtils.getEditableweightpsMapper().getWeightByNumber(thirdId, taskId);
                if (StringUtils.isBlank(weight3)) {
                    weight3 = thirdIdProblemDetail.get(i).getWeight3();
                }

                thirdMap.put("pName3", thirdIdProblemDetail.get(i).getpName3());
                thirdMap.put("weight3", weight3);
                thirdMap.put("point3", point3);
                allPoint += Double.valueOf(point3) * pointsCalculate.getPercentInstance(weight3);
                allWeight += pointsCalculate.getPercentInstance(weight3);
                thirdList.add(thirdMap);
            }
        }

        //遍历四级的管理行为
        List<ProblemCollectDetail> fourthIdProblemDetail = parProblemCollectDetailMapper.getAllCheckFourthInfoMXTQ(checkId);
        for (int i = 0; i < fourthIdProblemDetail.size(); i++) {
            if (fourthIdProblemDetail.get(i).getpName1().equals("管理行为")) {
                Map<String, Object> glFourthMap = new HashMap<>();
                String point4 = mapperUtils.getAllpointsaveMapper().getPointByCheckIdAndNumber(checkId, fourthIdProblemDetail.get(i).getFourthId());

                //更改权重来源
                int fourthId = fourthIdProblemDetail.get(i).getFourthId();
                String weight4 = mapperUtils.getEditableweightpsMapper().getWeightByNumber(fourthId, taskId);
                if (StringUtils.isBlank(weight4)) {
                    weight4 = fourthIdProblemDetail.get(i).getWeight4();
                }

                glFourthMap.put("pName4", fourthIdProblemDetail.get(i).getpName4());
                glFourthMap.put("weight4", weight4);
                glFourthMap.put("point4", point4);
                allPoint += Double.valueOf(point4) * pointsCalculate.getPercentInstance(weight4);
                allWeight += pointsCalculate.getPercentInstance(weight4);
                glFourthList.add(glFourthMap);
            }
        }

        //总得分：（Σ分项得分*分项权重）/Σ分项权重
        String allOverPoint = df.format(allPoint / allWeight);
        dataMap.put("thirdList", thirdList);
        dataMap.put("glFourthList", glFourthList);
        dataMap.put("allOverPoint", allOverPoint);

        //(三)、各专业问题分布情况
        List<Integer> pName4Info = parProblemCollectDetailMapper.getAllName4(checkId);
        int allProblemNum = parProblemCollectDetailMapper.getAllNum(checkId);
        dataMap.put("allProblemNum", allProblemNum);
        String name4 = JSON.toJSONString(pName4Info, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
        JSONArray name4Array = JSONArray.parseArray(name4);
        List<Object> part3List = new ArrayList<Object>();
        for (int m = 0; m < name4Array.size(); m++) {
            Map<String, Object> part3Map = new HashMap<String, Object>();
            int pName4Id = name4Array.getIntValue(m);
            String pName4 = parSystemMapper.getName4ByName4Id(pName4Id);
            int name4Num = parProblemCollectDetailMapper.countName4(pName4Id, checkId);
            String percent = pointsCalculate.caculateToPercent(name4Num, allProblemNum);
            part3Map.put("no", m + 1);
            part3Map.put("pName4", pName4);
            part3Map.put("problemNum", name4Num);
            part3Map.put("percent", percent);
            datasetPie.setValue(pName4 + ":" + percent, new Double(name4Num));
            datasetBar.addValue(name4Num, Bar, pName4);
            part3List.add(part3Map);
        }
        dataMap.put("problemList", part3List);
        //(四)、各专业问题饼图与直方图
        try {
            JFreeChart chart = ChartFactory.createPieChart("现场施工问题分布饼图", datasetPie, true, true, false);
            final PiePlot plot = (PiePlot) chart.getPlot();
            plot.setStartAngle(270);
            plot.setForegroundAlpha(0.90f);
            plot.setInteriorGap(0.02);
            chart.getLegend().setVisible(false);

            //地址
            //File pieChart = new File("D:\\Work\\LabWork\\YiRui\\文档\\Test\\" + dataMap.get("fileDate") + "pieChart.png");
            File pieChart = new File("D:\\whutServer\\generatedCharts\\" + dataMap.get("fileDate") + "pieChart.png");

            ChartUtils.saveChartAsPNG(pieChart, chart, WIDTH, HEIGHT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            JFreeChart barChart = ChartFactory.createBarChart("现场施工问题分布直方图",
                    "",
                    "数量",
                    datasetBar,
                    PlotOrientation.VERTICAL,
                    true, true, false);
            CategoryPlot plot = (CategoryPlot) barChart.getPlot();
            plot.getRenderer().setSeriesPaint(0, new Color(5, 87, 232));
            BarRenderer barRenderer = (BarRenderer) plot.getRenderer();
            barRenderer.setDefaultItemLabelGenerator(new StandardCategoryItemLabelGenerator());
            barRenderer.setDefaultItemLabelsVisible(true);
            barRenderer.setItemLabelAnchorOffset(-20D);
            barRenderer.setMaximumBarWidth(0.2);
            CategoryAxis categoryAxis = plot.getDomainAxis();
            categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45);

            //地址
            //File barChartFile = new File("D:\\Work\\LabWork\\YiRui\\文档\\Test\\" + dataMap.get("fileDate") + "barChart.png");
            File barChartFile = new File("D:\\whutServer\\generatedCharts\\" + dataMap.get("fileDate") + "barChart.png");

            ChartUtils.saveChartAsPNG(barChartFile, barChart, WIDTH, HEIGHT);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //地址
        //dataMap.put("pic6", MDoc.getImageStr("D:\\Work\\LabWork\\YiRui\\文档\\Test\\" + dataMap.get("fileDate") + "pieChart.png"));
        //dataMap.put("pic7", MDoc.getImageStr("D:\\Work\\LabWork\\YiRui\\文档\\Test\\" + dataMap.get("fileDate") + "barChart.png"));
        dataMap.put("pic6", MDoc.getImageStr("D:\\whutServer\\generatedCharts\\" + dataMap.get("fileDate") + "pieChart.png"));
        dataMap.put("pic7", MDoc.getImageStr("D:\\whutServer\\generatedCharts\\" + dataMap.get("fileDate") + "barChart.png"));

        //三、改进建议
        List<Object> part4List = new ArrayList<Object>();
        List<Integer> pName1Info = parProblemCollectDetailMapper.getAllName1Id(checkId);
        String name1 = JSON.toJSONString(pName1Info, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
        JSONArray name1Array = JSONArray.parseArray(name1);
        for (int i = 0; i < name1Array.size(); i++) {
            List<Object> part4InnerList = new ArrayList<Object>();
            Map<String, Object> part4Map = new HashMap<String, Object>();
            String pName1 = parSystemMapper.getName4ByName4Id(name1Array.getIntValue(i));
            List<Summary> summaryList = mapperUtils.getSummaryMapper().getSummaryInfo(checkId, name1Array.getIntValue(i));
            String summaryInfo = JSON.toJSONString(summaryList, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
            JSONArray summaryInfoArray = JSONArray.parseArray(summaryInfo);
            for (int j = 0; j < summaryInfoArray.size(); j++) {
                Map<String, Object> part4InnerMap = new HashMap<String, Object>();
                JSONObject part4InnerObject = summaryInfoArray.getJSONObject(j);
                String part4pNname4 = parSystemMapper.getName4ByName4Id(part4InnerObject.getIntValue("fourthId"));
                part4InnerMap.put("pName4", part4pNname4);
                part4InnerMap.put("summary", part4InnerObject.getString("summary"));
                part4InnerList.add(part4InnerMap);
            }
            if (pName1.equals("安全检查")||pName1.equals("新安全检查")) {
                part4Map.put("pName1", "安全");
            } else if (pName1.equals("质量检查")||pName1.equals("新质量检查")) {
                part4Map.put("pName1", "质量");
            } else if (pName1.equals("管理行为")||pName1.equals("新管理行为")) {
                part4Map.put("pName1", "管理行为");
            } else if (pName1.equals("设备检查") ||pName1.equals("新设备检查")){
                part4Map.put("pName1", "设备检查");
            }
            part4Map.put("summaryInnerList", part4InnerList);
            part4List.add(part4Map);
        }
        dataMap.put("summaryList", part4List);

        //四、问题汇总表
        List<Object> partProblemList = new ArrayList<Object>();
        for (int i = 0; i < name1Array.size(); i++) {
            List<Object> partProblemName1List = new ArrayList<Object>();
            Map<String, Object> partProblemMap = new HashMap<String, Object>();
            String pName1 = parSystemMapper.getName4ByName4Id(name1Array.getIntValue(i));
            List<Integer> problemName4List = parProblemCollectDetailMapper.getAllName4ByName1(checkId, pName1);
            String problemName4Info = JSON.toJSONString(problemName4List, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
            JSONArray problemName4Array = JSONArray.parseArray(problemName4Info);
            for (int k = 0; k < problemName4Array.size(); k++) {
                List<ProblemCollectDetail> partProblemDetailList = parProblemCollectDetailMapper.getAllFourthInfo(checkId, problemName4Array.getIntValue(k));
                String partProblemDetailInfo = JSON.toJSONString(partProblemDetailList, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                JSONArray partProblemDetailArray = JSONArray.parseArray(partProblemDetailInfo);
                String problemName4 = parSystemMapper.getName4ByName4Id(problemName4Array.getIntValue(k));
                for (int j = 0; j < partProblemDetailArray.size(); j++) {
                    Map<String, Object> partProblemName1Map = new HashMap<String, Object>();
                    JSONObject partProblemObject = partProblemDetailArray.getJSONObject(j);
                    String problemDescription = partProblemObject.getString("problemDescription");
                    String riskPoint = partProblemObject.getString("riskPoint");
                    if (partProblemObject.getString("isRemark").equals("N")) {
                        partProblemName1Map.put("problemDescription", problemDescription);
                    } else if (partProblemObject.getString("isRemark").equals("Y")) {
                        partProblemName1Map.put("problemDescription", partProblemObject.getString("remark"));
                    }
                    String riskLevel=" ";
                    switch(Integer.parseInt(partProblemObject.getString("riskPoint"))){
                        case 4:
                            riskLevel="一级";
                            break;
                        case 3:
                            riskLevel="二级";
                            break;
                        case 2:
                            riskLevel="三级";
                            break;
                        case 1:
                            riskLevel="四级";
                            break;
                    }
                    partProblemName1Map.put("riskPoint", riskLevel);
                    partProblemName1Map.put("pName4", problemName4);
                    partProblemName1List.add(partProblemName1Map);
                }
            }
            if (pName1.equals("安全检查")||pName1.equals("新安全检查")) {
                partProblemMap.put("pName1", "安全");
            } else if (pName1.equals("质量检查")||pName1.equals("新质量检查")) {
                partProblemMap.put("pName1", "质量");
            } else if (pName1.equals("管理行为")||pName1.equals("新管理行为")) {
                partProblemMap.put("pName1", "管理行为");
            } else if (pName1.equals("设备检查") ||pName1.equals("新设备检查")){
                partProblemMap.put("pName1", "设备检查");
            }
            partProblemMap.put("fourthProblemList", partProblemName1List);
            partProblemList.add(partProblemMap);
        }
        dataMap.put("allProblemList", partProblemList);
        int txNum = parProblemCollectDetailMapper.getAllRiskPointCountByType(checkId, "提醒");
        int oneNum = parProblemCollectDetailMapper.getAllRiskPointCountByType(checkId, "1");
        int twoNum = parProblemCollectDetailMapper.getAllRiskPointCountByType(checkId, "2");
        int threeNum = parProblemCollectDetailMapper.getAllRiskPointCountByType(checkId, "3");
        int fourNum = parProblemCollectDetailMapper.getAllRiskPointCountByType(checkId, "4");
        dataMap.put("txNum", txNum);
        dataMap.put("oneNum", oneNum);
        dataMap.put("twoNum", twoNum);
        dataMap.put("threeNum", threeNum);
        dataMap.put("fourNum", fourNum);
        String txPercent = pointsCalculate.caculateToPercent(txNum, allProblemNum);
        String onePercent = pointsCalculate.caculateToPercent(oneNum, allProblemNum);
        String twoPercent = pointsCalculate.caculateToPercent(twoNum, allProblemNum);
        String threePercent = pointsCalculate.caculateToPercent(threeNum, allProblemNum);
        String fourPercent = pointsCalculate.caculateToPercent(fourNum, allProblemNum);
        dataMap.put("txPercent", txPercent);
        dataMap.put("onePercent", onePercent);
        dataMap.put("twoPercent", twoPercent);
        dataMap.put("threePercent", threePercent);
        dataMap.put("fourPercent", fourPercent);
        //第二部分，各部分工程检查情况
        String section2pName1 = "";
        List<Object> section2List = new ArrayList<Object>();
        for (int b = 0; b < name1Array.size(); b++) {
            Map<String, Object> section2Name1Map = new HashMap<String, Object>();
            List<Object> section2name1List = new ArrayList<Object>();
            String section2name1 = parSystemMapper.getName4ByName4Id(name1Array.getIntValue(b));
            if (section2name1.equals("安全检查")||section2name1.equals("新安全检查")) {
                section2pName1 = "安全问题";
            } else if (section2name1.equals("质量检查")||section2name1.equals("新质量检查")) {
                section2pName1 = "质量问题";
            } else if (section2name1.equals("管理行为")||section2name1.equals("新管理行为")) {
                section2pName1 = "管理体系及管理动作";
            }
            section2Name1Map.put("section2pName1", section2pName1);
            List<Integer> section2Name4Info = parProblemCollectDetailMapper.getAllName4ByName1(checkId, section2name1);
            String section2Name44 = JSON.toJSONString(section2Name4Info, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
            JSONArray section2Name4Array = JSONArray.parseArray(section2Name44);
            for (int w = 0; w < section2Name4Array.size(); w++) {
                Map<String, Object> section2Name4Map = new HashMap<String, Object>();
                List<Object> section2Name4List = new ArrayList<Object>();
                int section2Name4Id = section2Name4Array.getIntValue(w);
                String section2Name4 = parSystemMapper.getName4ByName4Id(section2Name4Id);
                List<ProblemCollectDetail> section2Name6Info = parProblemCollectDetailMapper.getAllName6InfoByName4(checkId, section2Name4Id, section2name1);
                String section2Name66 = JSON.toJSONString(section2Name6Info, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                JSONArray section2Name6Array = JSONArray.parseArray(section2Name66);
                for (int c = 0; c < section2Name6Array.size(); c++) {
                    Map<String, Object> section2Name6Map = new HashMap<String, Object>();
                    List<Object> picList = new ArrayList<Object>();
                    JSONObject section2Name6Object = section2Name6Array.getJSONObject(c);
                    section2Name6Map.put("section2pName6No", c + 1);
                    section2Name6Map.put("section2pName6", section2Name6Object.getString("pName6"));
                    section2Name6Map.put("section2pName5", section2Name6Object.getString("pName5"));
                    String problemListRiskPoint = "";
                    switch (section2Name6Object.getString("riskPoint")) {
                        case "提醒":
                            problemListRiskPoint = "提醒";
                            break;
                        case "1":
                            problemListRiskPoint = "四级隐患";
                            break;
                        case "2":
                            problemListRiskPoint = "三级隐患";
                            break;
                        case "3":
                            problemListRiskPoint = "二级隐患";
                            break;
                        case "4":
                            problemListRiskPoint = "一级隐患";
                            break;
                        default:
                            problemListRiskPoint = "";
                            break;
                    }
                    section2Name6Map.put("section2RiskLevel", problemListRiskPoint);
                    section2Name6Map.put("section2CheckPart", section2Name6Object.getString("checkPart"));
                    section2Name6Map.put("section2ProblemNum", section2Name6Object.getString("problemQua"));
                    if (section2Name6Object.getString("isRemark").equals("N")) {
                        section2Name6Map.put("section2problemDescription", section2Name6Object.getString("problemDescription"));
                    } else if (section2Name6Object.getString("isRemark").equals("Y")) {
                        section2Name6Map.put("section2problemDescription", section2Name6Object.getString("remark"));
                    }
                    section2Name6Map.put("section2normsProvison", section2Name6Object.getString("normsProvison"));
                    section2Name6Map.put("section2suggestion", section2Name6Object.getString("suggestion"));
                    String section2picPath = section2Name6Object.getString("picPath");
                    String picName = section2Name6Object.getString("picName");
                    JSONArray ja = JSONArray.parseArray(picName);
                    if (ja.size() == 0) {

                        //地址
                        String s = MDoc.getImageStr("D:\\whutServer\\generatedCharts\\noPic.png");

                        picList.add(s);
                    } else {
                        for (int o = 0; o < ja.size(); o++) {
                            String s = "";
                            if ("prod".equals(profiles.getActives())) {
                                s = MDoc.getImageStr(section2picPath + ja.getString(o));
                            }
                            //地址
//                            String s = MDoc.getImageStr("D:\\whutServer\\generatedCharts\\noPic.png");

                            picList.add(s);
                        }
                    }
                    section2Name6Map.put("picList", picList);
                    section2Name4List.add(section2Name6Map);

                }
                section2Name4Map.put("section2pName4", section2Name4);
                section2Name4Map.put("section2Name4List", section2Name4List);
                section2name1List.add(section2Name4Map);
            }
            section2Name1Map.put("section2Name1List", section2name1List);
            section2List.add(section2Name1Map);
        }
        dataMap.put("section2List", section2List);
        MDoc mdoc = new MDoc();
        String path = FileUtil.getServerFolderPath();
        File f1 = new File(path, "doc");
        if (!f1.exists()) {
            f1.mkdirs();
        }
        String result = "";
        if (reportType == 8) {
            DateTimeFormatter dateTime = DateTimeFormatter.ofPattern("yyyyMMddhhmmss");
            String fileNameTime = dateTime.format(LocalDateTime.now());
            String reportName = String.valueOf(dataMap.get("projectName")).replace('#', '号') + "安全报告" + fileNameTime ;
            String ftlName = "aqMXTQ";

           // BeanMap beanMap = new BeanMap(dataMap);
            return ReportCommonFunc.generateReport(dataMap, reportName, ftlName);

        } else if (reportType == 9) {
            DateTimeFormatter dateTime = DateTimeFormatter.ofPattern("yyyyMMddhhmmss");
            String fileNameTime = dateTime.format(LocalDateTime.now());
            String reportName = String.valueOf(dataMap.get("projectName")).replace('#', '号') + "质量报告" + fileNameTime  ;
            String ftlName = "Risk2.0";

            //BeanMap beanMap = new BeanMap(dataMap);
            return ReportCommonFunc.generateReport(dataMap, reportName, ftlName);

       }
        return null;
    }
}
